<template>
  <div ref="qrcode"></div>
</template>  
  
<script>
// 引入qrcodejs2
import QRCode from 'qrcodejs2'
export default {
  name: 'QrCodeComponent',
  props: {
    // 可以通过props传递二维码的内容
    qrText: {
      type: String,
      required: true
    },
    height: {
      type: Number,
      default: 200
    },
    width: {
      type: Number,
      default: 200
    },
    colorDark: {
      type: String,
      default: '#000000'
    },
    colorLight: {
      type: String,
      default: '#ffffff'
    }
  },
  data () {
    return {
      qrCode: null
    }
  },
  mounted() {
    // 组件挂载后生成二维码
    this.generateQRCode()
  },
  methods: {
    generateQRCode() {
      // 使用this.$refs访问DOM元素
      if (!this.qrCode) {
        this.qrCode = new QRCode(this.$refs.qrcode, {
          text: this.qrText,
          width: this.width,
          height: this.height,
          colorDark: this.colorDark,
          colorLight: this.colorLight,
          correctLevel: QRCode.CorrectLevel.H
        })
      }
      this.qrCode.clear()
      this.qrCode.makeCode(this.qrText);
    }
  },
  // 如果二维码内容会变化，可以添加watch来重新生成二维码
  watch: {
    qrText() {
      this.generateQRCode()
    }
  }
}
</script>  
  
<style lang="scss" scoped>

</style>